<?php

namespace app\admin\system\logic;

use app\admin\system\service\AdminService;
use app\common\logic\BaseLogic;
use app\model\SysMenu;
use app\model\SysRoleMenu;
use core\utils\TreeUtil;

class MenuLogic extends BaseLogic
{
    public function __construct()
    {
        $this->model = new SysMenu();
    }

    public function myLoginAuth($uid)
    {
        $isSuperAdmin = AdminService::isSuperAdmin($uid);
        $result = [
            "dashboardGrid" => [],
            "menu" => [],
            'permissions' => ['*']
        ];
        if ($isSuperAdmin) {
            $data = SysMenu::alias('a')
                ->order("a.sort")
                ->select()
                ->toArray();
        } else {
            $role_ids = AdminService::getRoleIdsByUid($uid);
            $data = SysMenu::alias('a')
                ->join(SysRoleMenu::getTable() . ' b', 'a.id=b.menu_id')
                ->where('b.role_id', 'in', $role_ids)
                ->order("a.sort")
                ->field([
                    "a.*",
                ])
                ->select()
                ->toArray();
            $result['permissions'] = array_column($data, 'auth');
        }
        foreach ($data as &$item) {
            $item['meta'] = [
                'title' => $item['title'],
                'type' => $item['type'],
                'icon' => $item['icon'],
                'affix' => $item['affix'],
                'hidden' => $item['hidden'],
                'fullpage' => $item['fullpage'],
            ];
            unset(
                $item['title'],
                $item['type'],
                $item['icon'],
                $item['affix'],
                $item['hidden'],
                $item['fullpage'],
            );
        }

        $result['menu'] = TreeUtil::getTree($data);
        return $result;
    }

}